/**
 * @author yinyuejia
 * @file 权限验证（封装成指令）
 */

import { useStore } from 'vuex';
import typeUtil from '@/utils/type';

export const permissionHandler = (value: any, and: any) => {
  const roles = useStore().state.user.permissions;
  let hasPermission = false;
  if (value) {
    let checkValue: any = [];
    if (typeUtil.isArray(value)) {
      checkValue = checkValue.concat(value);
    }
    if (typeUtil.isString(value)) {
      checkValue.push(value);
    }
    if (checkValue.length > 0) {
      if (and) {
        hasPermission = checkValue.every((role: any) => roles.includes(role));
      } else {
        hasPermission = checkValue.some((role: any) => roles.includes(role));
      }
    }
  }
  return hasPermission;
};

// 指令执行时机
export default {
  mounted(el: any, binding: any) {
    if (!permissionHandler(binding.value, binding.modifiers.and)) {
      el.parentNode && el.parentNode.removeChild(el);
    }
  },
  updated(el: any, binding: any) {
    if (!permissionHandler(binding.value, binding.modifiers.and)) {
      el.parentNode && el.parentNode.removeChild(el);
    }
  },
};
